package com.codeduck.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeduck.common.dubbo.IAccountDubboService;
import com.codeduck.common.enums.MicroExceptionEnum;
import com.codeduck.common.enums.ResEnum;
import com.codeduck.common.exception.MicroException;
import com.codeduck.common.response.AccountResponse;
import com.codeduck.common.response.ServiceResponse;
import com.codeduck.order.domain.OrderDO;
import com.codeduck.order.mapper.OrderMapper;
import com.codeduck.order.service.IOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.UUID;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-08-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderDO> implements IOrderService {

    @Resource
    private IAccountDubboService accountDubboService;

    @Override
    public OrderDO createOrder(String userId, String commodityCode, int count) {
        // 扣减用户账户
        BigDecimal orderMoney = calculate(commodityCode, count);
        ServiceResponse<AccountResponse> accountServiceResponse = accountDubboService.decreaseAccount(userId, orderMoney);

        // 生成订单
        String orderNo = UUID.randomUUID().toString().replace("-","");
        OrderDO orderDO = OrderDO.builder()
                .orderNo(orderNo)
                .userId(userId)
                .commodityCode(commodityCode)
                .count(count)
                .amount(orderMoney)
                .build();
        int insert = this.baseMapper.insert(orderDO);
        if (insert == 0) {
            throw new MicroException(MicroExceptionEnum.CREATE_ORDER_FAIL.getMessage());
        }
        if (null == accountServiceResponse || accountServiceResponse.getCode().equals(ResEnum.FAILED)) {
            throw new MicroException(MicroExceptionEnum.DECREASE_ACCOUNT_FAIL.getMessage());
        }
        return orderDO;
    }

    private BigDecimal calculate(String commodityCode, int count) {
        String code_1 = "C201901140001";
        BigDecimal code_1_money = new BigDecimal(19.9);
        if (commodityCode.equals(code_1)) {
            return code_1_money.multiply(new BigDecimal(count));
        }
        return new BigDecimal(0);
    }
}
